<template>
  <div v-loading="loading">
    <table class="table table-bordered vertical-align-middle text-center">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td>主体姓名</td>
          <td colspan="3" class="text-left">{{ relatedData.customer_name || '' }}</td>
        </tr>
        <tr>
          <td>授信开始时间</td>
          <td>{{ relatedData.loadDateCredit }}</td>
          <td>授信结束时间</td>
          <td>{{ relatedData.loadEndDateCredit }}</td>
        </tr>
        <tr>
          <td>授信金额（万元）</td>
          <td>{{ relatedData.reply_funds }}</td>
          <td>授信期限（月）</td>
          <td>{{ relatedData.period_credit }}</td>
        </tr>

        <tr>
          <td>
            <span class="text-danger" v-if="!viewMode">*</span>
            放款开始时间
          </td>
          <td :class="tdClass">
            <span class="px-2" v-if="viewMode">
              {{ $utils.dateFormat(relatedData.load_date, 'yyyy年MM月dd日') }}
            </span>
            <el-date-picker
              v-else
              v-model="editData.load_date"
              :clearable="false"
              type="date"
              placeholder="放款开始时间"
              class="w-100"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </td>
          <td>
            <span class="text-danger" v-if="!viewMode">*</span>
            放款结束时间
          </td>
          <td :class="tdClass">
            <span class="px-2" v-if="viewMode">
              {{ $utils.dateFormat(relatedData.load_end_date, 'yyyy年MM月dd日') }}
            </span>
            <el-date-picker
              v-else
              v-model="editData.load_end_date"
              :clearable="false"
              type="date"
              placeholder="放款结束时间"
              class="w-100"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </td>
        </tr>
        <tr>
          <td>
            <span class="text-danger" v-if="!viewMode">*</span>
            放款金额（万元）
          </td>
          <td :class="tdClass">
            <span v-if="viewMode">{{ relatedData.warranty_amount }}</span>
            <el-input
              v-else
              placeholder="放款金额"
              clearable
              v-input-number="{ min: 0, fixed: 2 }"
              v-model="editData.warranty_amount"
            >
              <span slot="append">万元</span>
            </el-input>
          </td>
          <td>放款期限（月）</td>
          <td>
            <span v-if="viewMode">{{ relatedData.warranty_period }}</span>
            <span v-else>{{ loanPeriod }}</span>
          </td>
        </tr>
        <tr>
          <td>
            <span class="text-danger" v-if="!viewMode">*</span>
            借据号
          </td>
          <td :class="tdClass">
            <span v-if="viewMode">{{ relatedData.iou_no }}</span>
            <el-input
              v-else
              v-model="editData.iou_no"
              placeholder="借据号"
              class="w-100"
            ></el-input>
          </td>
          <td></td>
          <td></td>
        </tr>
        <tr>
          <td>放款凭证（借据）</td>
          <td colspan="3" class="text-left">
            <div v-if="viewMode">
              <div class="empty-wrap" v-if="!attachList.length">暂无附件（借据）</div>
              <attach-list v-else :attath-data="viewList" :show-label="false"></attach-list>
            </div>
            <upload-oss
              v-else
              multiple
              ref="attachUpload"
              :dir="dir"
              :file-list="attachList"
              :on-complete="handleAttachComplete"
            ></upload-oss>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="text-center" v-if="!viewMode">
      <el-button class="btn-long" type="primary" @click="handlePass" :loading="submitLoading">
        登记
      </el-button>
      <el-button class="btn-long" @click="beforeClose" :loading="submitLoading">取消</el-button>
    </div>
  </div>
</template>

<script>
import { dataAdapter, countMonth } from '@/bank/views/business/hplimit/enum'
import { attachAdapter } from '@/bank/components/attach/index'
import { deleteOss } from '@/common/api/oss'
import AttachList from '@/bank/views/business/limit/history/attach/AttachList'
export default {
  components: { AttachList },
  props: {
    viewMode: { type: Boolean, default: true },
    queryId: String,
  },
  data() {
    return {
      tableName: 'datum_one_county_industry',
      relatedData: {},
      editData: {
        load_date: '',
        load_end_date: '',
        warranty_amount: '',
        iou_no: '',
      },
      loading: false,
      attachList: [],
      viewList: [],
      parentTag: '放款登记附件',
      attachTag: '借据号',
      submitLoading: false,
    }
  },
  computed: {
    tdClass() {
      return this.viewMode ? '' : 'input-td'
    },
    dir() {
      return `credit/normal/register/${this.queryId}`
    },
    loanPeriod() {
      return countMonth(this.editData.load_date, this.editData.load_end_date)
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (this.queryId) {
          this.getData()
          this.getAttach()
        }
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleAttachComplete(files) {
      const { attachAready } = this
      const addFiles = files.filter(file => !attachAready.find(it => it.attachment === file.url))
      const deleteFiles = attachAready.filter(it => !files.find(file => file.url === it.attachment))

      const promise = []
      if (files.length) {
        promise.push(
          this.$api.addBatch(
            'credit',
            'datum_customer_attachment',
            addFiles.map(it => ({
              attachment: it.url,
              attachment_type: this.attachTag,
              parent_attachment_type: this.parentTag,
              customer_related_id: this.queryId,
              file_type: 2,
              remark: it.name,
            }))
          )
        )
      }
      if (deleteFiles.length) {
        promise.push(
          this.$api.deleteData({
            table: 'datum_customer_attachment',
            id: deleteFiles.map(it => it.id).join(','),
          }),
          deleteOss(deleteFiles.map(it => it.attachment))
        )
      }
      Promise.all(promise).then(() => {
        this.getAttach()
      })
      this.registerData()
        .then(() => {
          this.$message.success('登记成功！')
          this.$emit('success', true)
          this.beforeClose()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    registerData() {
      const data = {
        ...this.editData,
        is_register: 1,
      }
      return this.$api.updateData(this.$serviceName, this.tableName, this.queryId, data)
    },
    handlePass() {
      if (!this.editData.load_date) {
        return this.$message.error('请选择放款开始时间')
      }

      if (!this.editData.load_end_date) {
        return this.$message.error('请选择放款结束时间')
      }
      if (this.editData.load_end_date < this.editData.load_date) {
        return this.$message.error('放款结束时间不能小于等于放款开始时间')
      }

      if (!this.editData.iou_no) {
        return this.$message.error('请输入借据号')
      }

      this.onSave()
    },
    onSave() {
      this.$utils
        .msgbox({
          message: `确定登记?`,
          type: 'info',
          beforeClose: () => {
            this.submitLoading = true
            this.$refs.attachUpload.submit()
          },
        })
        .catch(() => this.$message.error(`登记失败，请重试！`))
    },
    getAttach() {
      if (!this.queryId) {
        return
      }
      this.$api
        .getData({
          table: 'datum_customer_attachment',
          params: {
            'customer_related_id.eq': this.queryId,
            'attachment_type.eq': this.attachTag,
          },
        })
        .then(res => {
          this.attachAready = res?.data ?? []
          this.attachList = this.attachAready.map(attachAdapter)
          this.viewList = [
            {
              tag: this.attachTag,
              attachs: this.attachList,
            },
          ]
        })
    },
    getData() {
      this.loading = true
      this.$api
        .getDataFromId(this.$serviceName, this.tableName, this.queryId)
        .then(res => {
          this.relatedData = dataAdapter(res?.data ?? {})
          Object.keys(this.editData).forEach(key => {
            this.editData[key] = this.relatedData[key] || ''
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    beforeClose() {
      this.$emit('dismiss', false)
    },
  },
}
</script>

<style lang="scss" scoped></style>
